<template>
  <div class="white-box">
    <div class="table-mb">
      <el-button type="primary" @click="handleAdd2()" :icon="CirclePlus">创建用户</el-button>
    </div>

    <div class="task-one">
      <div class="task-one__item">
        <span class="task-one__label">手机号：</span>
        <el-input placeholder="请输入手机号" v-model="searchParams.phone" @keyup.enter.native="handleSearch" clearable></el-input>
      </div>
      <div class="task-one__item">
        <span class="task-one__label">登录账号：</span>
        <el-input placeholder="请输入登录账号" v-model="searchParams.userName" @keyup.enter.native="handleSearch" clearable></el-input>
      </div>
      <div class="task-one__item">
        <span class="task-one__label">性别：</span>
        <el-select v-model="searchParams.sex" placeholder="请选择性别" clearable>
          <el-option :label="item.label" :value="item.value" v-for="(item, index) in selectOptions.sex"
                     :key="index"/>
        </el-select>
      </div>
      <div class="task-one__item">
        <span class="task-one__label">状态：</span>
        <el-select v-model="searchParams.status" placeholder="请选择状态" clearable>
          <el-option :label="item.label" :value="item.value" v-for="(item, index) in selectOptions.status"
                     :key="index"/>
        </el-select>
      </div>
      <div class="task-one__btn">
        <el-button type="primary" :loading="searchBtnLoading" :icon="Search"
                   @click="handleSearch">搜索</el-button>
        <el-button type="success" :loading="importDataBtnLoading" @click="importData('users/export-list-user')"
                   :icon="Download">导出</el-button>
      </div>
    </div>

    <el-table class="table-mb" v-loading="loading" :data="list" :header-cell-style="{ background: '#F5F7FA' }"
              element-loading-background="rgba(255, 255, 255, 0.6)">
      <!--      <el-table-column prop="sid" label="sid" width="50"></el-table-column>-->
      <el-table-column prop="avatar" label="头像"  align="center" min-width="66" max-width="66" width="66">
        <template #default="{ row }">
          <el-avatar :size="40" :src="proxy.imgUrl + row.avatar" style="display: block">
            <img :src="defaultAvatar"/>
          </el-avatar>
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="手机号"></el-table-column>
      <el-table-column prop="nickName" label="用户名">
        <template #default="{ row }">
          <span style="margin-right: 10px;display: inline-block">{{row.nickName}}</span>
          <el-icon v-if="row.sex === 0">
            <Male color="#409eff"/>
          </el-icon>
          <el-icon v-if="row.sex === 1">
            <Female color="#f89898"/>
          </el-icon>
        </template>
      </el-table-column>
      <el-table-column prop="points" label="积分" width="100">
        <template #default="{ row }">
          <div v-if="row.balance">
            {{row.balance.points}}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="dominate" label="总佣金" width="100">
        <template #default="{ row }">
          <div v-if="row.balance">
            {{row.balance.dominate}}
          </div>
        </template>
      </el-table-column>
<!--      <el-table-column prop="userName" label="登录账号"> </el-table-column>-->

      <el-table-column prop="referralCode" label="推荐码"></el-table-column>
      <el-table-column prop="referralMember" label="推荐人" min-width="140">
        <template #default="{ row }">
          <div style="display: flex;align-items: center;" v-if="row.referralMember">
            <el-avatar :size="40" :src="proxy.imgUrl + row.referralMember.avatar">
              <img :src="defaultAvatar"/>
            </el-avatar>
            <div style="margin-left: 10px">
              <div><el-text type="info">昵称：</el-text>{{row.referralMember.nickName}}</div>
              <div><el-text type="info">手机号：</el-text>{{row.referralMember.phone}}</div>
            </div>
          </div>

        </template>
      </el-table-column>
      <el-table-column align="center" prop="status" label="状态"  width="100">
        <template #default="{ row }">
          <el-text v-if="row.status === 0" type="success">正常</el-text>
          <el-text v-else-if="row.status === 1" type="info">停用</el-text>
          <el-text v-else type="info"></el-text>
        </template>
      </el-table-column>
      <el-table-column prop="created" label="创建时间" width="160"> </el-table-column>
      <el-table-column label="操作" width="320" fixed="right" min-width="320">
        <template #default="{ row }">
          <div v-if="!row.roleNames.includes('最高管理员')">
            <div style="margin-bottom: 6px">
              <el-button link type="primary" @click="toDetail(row.sid)">查看详情</el-button>
<!--              <el-button link type="primary" @click="handleEdit2(row,{sid:row.sid})">编辑信息</el-button>-->
              <el-button link type="primary" @click="handleChangPassword(row)">修改密码</el-button>
              <el-button link type="primary" @click="handleLowers(row)">查看下级</el-button>
<!--              <el-popconfirm :persistent="false" title="确定更改该用户的状态吗？" confirm-button-text="确定" cancel-button-text="取消"-->
<!--                             @confirm="handleAction('put',`/users/${row.sid}/status`)">-->
<!--                <template #reference>-->
<!--                  <el-button link type="primary">更改状态</el-button>-->
<!--                </template>-->
<!--              </el-popconfirm>-->
              <el-popconfirm :persistent="false" title="确定删除吗？" confirm-button-text="确定" cancel-button-text="取消"
                             @confirm="handleDelete(row.sid)">
                <template #reference>
                  <el-button link type="danger">删除用户</el-button>
                </template>
              </el-popconfirm>
            </div>
            <div>
              <el-button link type="success" @click="handleFinance(row)">佣金明细</el-button>
              <el-button link type="primary" @click="handleChangCommission(row)">变更佣金</el-button>
              <el-button link type="success" @click="handlePointslist(row)">积分明细</el-button>
              <el-button link type="primary" @click="handleChangPoints(row)">变更积分</el-button>
            </div>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        background
        v-model:current-page="page"
        v-model:page-size="pageSize"
        :page-sizes="pageSizeNum"
        :total="totalNums"
        layout="total, sizes, prev, pager, next, jumper"
    >
    </el-pagination>

    <el-dialog v-model="dialogShow" :title="dialogParams.type === 'add'?'添加':'编辑'" width="660px" :append-to-body="true" :destroy-on-close="true" :close-on-click-modal="false" @close="closeDialog">
      <el-form ref="dialogFormRef" :model="dialogForm" :rules="dialogFormRules" label-width="120px" style="width: 550px">
        <el-form-item label="登录账号" prop="userName" required>
          <el-input v-model.trim="dialogForm.userName" clearable placeholder="请输入登录账号" maxlength="20" :disabled="dialogParams.type != 'add'"/>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model.trim="dialogForm.phone" maxlength="11" clearable placeholder="请输入手机号" oninput="value=value.replace(/[^\d]/g,'')"  :disabled="dialogParams.type != 'add'"/>
        </el-form-item>
        <el-form-item label="登录密码" prop="password" required v-if="dialogParams.type === 'add'">
          <el-input
              v-model.trim="dialogForm.password"
              placeholder="登录密码"
              clearable
              show-password
              style="width: 45%"
          >
          </el-input>
          <el-text type="danger" style="margin-left: 5px">密码长度6-20位，由字母或数字组成</el-text>
        </el-form-item>
        <el-form-item label="用户名" prop="nickName">
          <el-input v-model.trim="dialogForm.nickName" clearable placeholder="请输入用户名" maxlength="20"/>
        </el-form-item>
        <el-form-item label="推荐码" prop="referralCode">
          <el-input v-model.trim="dialogForm.referralCode" clearable placeholder="请输入推荐码" maxlength="20"/>
        </el-form-item>
        <el-form-item label="头像" prop="avatar">
          <File-upload ref="avatarRef" v-model="dialogForm.avatar" :fileSize="50" :limit="1" modelValueType="String" :fileType="['png', 'jpg', 'jpeg']" listType="picture-card"></File-upload>
        </el-form-item>
        <el-form-item label="生日" prop="birth">
          <el-date-picker
              v-model="dialogForm.birth"
              type="date"
              placeholder="请选择"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              clearable
          />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model.trim="dialogForm.email" clearable placeholder="请输入邮箱"/>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="dialogForm.sex">
            <el-radio :value="0">男</el-radio>
            <el-radio :value="1">女</el-radio>
            <el-radio :value="2">未知</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="note">
          <el-input v-model.trim="dialogForm.note" clearable placeholder="请输入备注"/>
        </el-form-item>
        <!--        <el-form-item label="角色" prop="roleSids">-->
        <!--          <el-select-->
        <!--              v-model="dialogForm.roleSids"-->
        <!--              multiple-->
        <!--              placeholder="请选择"-->
        <!--          >-->
        <!--            <el-option-->
        <!--                v-for="item in selectOptions.roleSids"-->
        <!--                :key="item.value"-->
        <!--                :label="item.label"-->
        <!--                :value="item.value"-->
        <!--            />-->
        <!--          </el-select>-->
        <!--        </el-form-item>-->
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="dialogForm.status">
            <el-radio :value="0">正常</el-radio>
            <el-radio :value="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <div class="flexs">
            <el-button type="primary" :loading="dialogParams.loading" @click="submitDialogForm2(dialogFormRef)">
              确认
            </el-button>
            <el-button @click="resetDialogForm(dialogFormRef)">重置</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog v-model="finance_dialogShow" :title="`佣金明细（用户：${finance_dialogParams.row.phone}）`" width="1000px" :append-to-body="true" :destroy-on-close="true" :close-on-click-modal="false" @close="finance_closeDialog">
      <div style="height: 600px;">
        <commissionList v-if="finance_dialogShow" :user-sid="finance_dialogParams.row.sid"></commissionList>
      </div>
    </el-dialog>
    <el-dialog v-model="pointslist_dialogShow" :title="`积分日志（用户：${pointslist_dialogParams.row.phone}）`" width="1200px" :append-to-body="true" :destroy-on-close="true" :close-on-click-modal="false" @close="pointslist_closeDialog">
      <div style="height: 600px;">
        <pointsList v-if="pointslist_dialogShow" :user-sid="pointslist_dialogParams.row.sid"></pointsList>
      </div>
    </el-dialog>
    <el-dialog v-model="lowers_dialogShow" :title="`直推下级（用户：${lowers_dialogParams.row.phone}）`" width="1000px" :append-to-body="true" :destroy-on-close="true" :close-on-click-modal="false" @close="lowers_closeDialog">
      <div style="height: 600px;">
        <lowers v-if="lowers_dialogShow" :user-sid="lowers_dialogParams.row.sid"></lowers>
      </div>
    </el-dialog>

    <changCommission :show="commission_dialogShow" :data="commission_dialogParams" @close="commission_closeDialog"></changCommission>
    <changPoints :show="points_dialogShow" :data="points_dialogParams" @close="points_closeDialog"></changPoints>
    <changPassword :show="cp_dialogShow" :data="cp_dialogParams" @close="cp_closeDialog"></changPassword>



    <go-back/>
  </div>
</template>

<script setup>
import {
  getCurrentInstance,
  ref,
  reactive,
  onMounted,
  watch,
  computed
} from "vue"
import commissionList from "@/views/Commission/CommissionList.vue";
import pointsList from "@/views/Points/PointsList.vue";
import lowers from "./components/lowers.vue";
import changPassword from "./components/changPassword.vue";
import changPoints from "./components/changPoints.vue";
import changCommission from "./components/changCommission.vue";
import listMixins from "@mixins/hook/list"
import {
  useRouter
} from "vue-router"
import {
  CirclePlus, Download, Lock, Search
} from "@element-plus/icons-vue"
import GoBack from "@components/GoBack.vue"
import JSEncrypt from "jsencrypt";
import FileUpload from "@components/FileUpload.vue";

const router = useRouter()
const {
  proxy
} = getCurrentInstance()

/**
 * minxin列表加载
 */
const {
  page,
  pageSizeNum,
  pageSize,
  loading,
  totalNums,
  searchParams,
  searchBtnLoading,
  apiPath,
  listApiPath,
  list,
  dialogFormRef,
  dialogShow,
  dialogForm,
  dialogParams,
  handleSearch,
  getData,
  handleAdd,
  handleEdit,
  resetDialogForm,
  handleAllSelected,
  submitDialogForm,
  closeDialog,
  handleAction,
  handleDelete,
  importData,
  importDataBtnLoading
} = listMixins()

const selectOptions = reactive({
  roleSids: [],
  sex: [
    {label: '未知', value: 2},
    {label: '男', value: 0},
    {label: '女', value: 1},
  ],
  status: [
    {label: '正常', value: 0},
    {label: '停用', value: 1},
  ]
})

dialogForm.avatar = "";//头像
dialogForm.referralCode = "";//推荐码
dialogForm.birth = "";//生日：yyyy-MM-dd
dialogForm.email = "";//邮箱
dialogForm.nickName = "";//昵称，最大长度 20位
dialogForm.note = "";//备注，最多100字符
dialogForm.password = "";//密码，长度6-20位，支持数字字母以及!@#$%^&*_，需要使用公钥加密
dialogForm.phone = "";//手机号，11位
dialogForm.roleSids = ['2-26ffdaf4817a4240b7a07cd4093efa70'];//所属角色sid列表
dialogForm.sex = 2;//性别：0=男, 1=女, 2=未知；默认2
dialogForm.status = 0;//状态：0=正常, 1=停用；默认0
dialogForm.userName = "";//用户名，最大长度 20位

listApiPath.value = '/users/client';
apiPath.value = '/users';

onMounted(() => {
  getData()
  getRolesAll()
  getKey();
})
const dialogFormRules = reactive({
  nickName: [{
    required: true,
    message: "请输入登录账号",
    trigger: "blur"
  }],
  password: [{
    required: true,
    message: "请输入登录密码",
    trigger: "blur"
  }],
  phone: [{
    required: true,
    message: "请输入手机号",
    trigger: "blur"
  }],
})
const submitDialogForm2 = (dialogFormRef) => {
  let data = JSON.parse(JSON.stringify(dialogForm));
  if (data.password) {
    let encryptor = new JSEncrypt() // 创建加密对象实例
    encryptor.setPublicKey(pub_keys.value) // 设置公钥
    data.password = encryptor.encrypt(data.password) // 对内容进行加密
  }
  submitDialogForm(dialogFormRef, data)
}
// 编辑修改用户，不提交密码
const handleEdit2 = (row, data) => {
  delete dialogForm.password
  handleEdit(row, data);
}
// 创建用户
const handleAdd2 = (data, row) => {
  dialogForm.password = '';
  handleAdd(row, data);
}
//修改密码
const handleChangPassword = (row) => {
  cp_dialogParams.row = row;
  cp_dialogShow.value = true;
}
const cp_dialogShow = ref(false);
const cp_dialogParams = reactive({
  loading: false,
  row: {}
});
const cp_closeDialog = (isSubmit) => {
  cp_dialogShow.value = false
  if(isSubmit){
    getData();
  }
}
// 变更积分
const handleChangPoints = (row) => {
  points_dialogParams.row = row;
  points_dialogShow.value = true;
}
const points_dialogShow = ref(false);
const points_dialogParams = reactive({
  loading: false,
  row: {}
});
const points_closeDialog = (isSubmit) => {
  points_dialogShow.value = false
  if(isSubmit){
    getData();
  }
}
// 变动佣金
const handleChangCommission = (row) => {
  commission_dialogParams.row = row;
  commission_dialogShow.value = true;
}
const commission_dialogShow = ref(false);
const commission_dialogParams = reactive({
  loading: false,
  row: {}
});
const commission_closeDialog = (isSubmit) => {
  commission_dialogShow.value = false
  if(isSubmit){
    getData();
  }
}
// 变动佣金 end
const getRolesAll = async () => {
  await proxy.$axios
      .get('/roles/all')
      .then((res) => {
        switch (res.data.code) {
          case 200:
            let resData = res.data.data
            selectOptions.roleSids = resData.map(v => {
              return {
                label: v.roleName,
                value: v.sid
              }
            })
            break
          default:
            proxy.$message({message: res.data.msg, type: "error"})
            break
        }
        loading.value = false;
      })
      .catch((error) => {
        loading.value = false;
      })
}

const pub_keys = ref("")

function getKey() {
  proxy.$axios
      .get("authentication/public-key")
      .then((res) => {
        if (res.data.code === 200) {
          pub_keys.value = res.data.data
        } else {
          proxy.$message({message: res.data.msg, type: "error"})
        }
      })
      .catch((err) => {
      })
}
// 佣金明细
const finance_dialogParams = reactive({
  loading: false,
  row: {}
});
const handleFinance = (row) =>{
  finance_dialogParams.row = row;
  finance_dialogShow.value = true
}
const finance_dialogShow = ref(false)
const finance_closeDialog = () => {
  finance_dialogShow.value = false
}
// 积分日志
const pointslist_dialogParams = reactive({
  loading: false,
  row: {}
});
const handlePointslist = (row) =>{
  pointslist_dialogParams.row = row;
  pointslist_dialogShow.value = true
}
const pointslist_dialogShow = ref(false)
const pointslist_closeDialog = () => {
  pointslist_dialogShow.value = false
}
// 查看下级
const lowers_dialogParams = reactive({
  loading: false,
  row: {}
});
const handleLowers = (row) =>{
  lowers_dialogParams.row = row;
  lowers_dialogShow.value = true
}
const lowers_dialogShow = ref(false)
const lowers_closeDialog = () => {
  lowers_dialogShow.value = false
}

const toDetail = (sid) => {
  router.push({
    path: "/Client/ClientDetail",
    query: {
      sid:sid
    }
  })
}

</script>

<style lang="less">

</style>